<?php namespace Summer\Userhub;

use RainLab\User\Controllers\Users as UsersController;
use RainLab\User\Models\Settings as UserSettings;
use RainLab\User\Models\User as UserModel;
use Summer\Hjd\Models\WalletModel;
use System\Classes\PluginBase;
use Yaml;
use File;
use Validator;
use Event;
use Input;
use Config;
use ApplicationException;

class Plugin extends PluginBase
{
    public $require = ['RainLab.User'];

    public function registerComponents()
    {
    }

    public function registerSettings()
    {
    }

    public function boot()
    {
        $this->extendUserModel();
        $this->extendUsersController();

    }
    protected function extendUserModel()
    {
        $user_first=UserModel::first();
        UserModel::extend(function($model) use($user_first){
            $model->implement[] = 'Summer.Location.Behaviors.LocationModel';
            //清除需要填写但不必存库的字段
            $model->addPurgeable([
                'password_safe_confirmation',//确认安全密码
                'tuijian_number',//推荐人号码，可以是编号，手机号或邀请码
            ]);
            //可写入参数
            $model->addFillable([
                'password_safe',//安全密码
                'userphone',//手机号
                'realname',//真实姓名
                'nickname',//昵称
                'birthday',//生日
                'openid',//openid
                //地址信息
                'province_code',//省级编号
                'city_code',//市级编号
                'area_code',//区县编号
                'street_addr',//街道地址
            ]);
            //自动哈希加密
            $model->addHashable([
                'password_safe'
            ]);
            //关联关系
            $model->hasOne =[
                //会员级别
                'leveluinfo'=>[
                    'Summer\Hjd\Models\LeveluModel',
                    'key'=>'id',
                    'otherKey'=>'levelu_code',
                ],
                //推荐人信息
                'tuijianinfo'=>[
                    'RainLab\User\Models\User',
                    'key'=>'id',
                    'otherKey'=>'tuid',
                ],
                //星级级别
                'levelsinfo'=>[
                    'Summer\Hjd\Models\LevelsModel',
                    'key'=>'id',
                    'otherKey'=>'levels_code',
                ],
            ];
            //关联关系
            $model->hasMany =[
                //钱包
                'wallets'=>[
                    'Summer\Hjd\Models\WalletModel',
                    'key'=>'user_id',
                ],
                //第三方绑定
                'oauth'=>[
                    'Summer\Userhub\Models\OauthModel',
                    'key'=>'user_id',
                ],
            ];
            $model->attachOne['wechat_cover'] =\System\Models\File::class;
            $model->attachOne['alipay_cover'] =\System\Models\File::class;

            $model->rules['userphone']='nullable|mobile|unique:users';//手机号验证，唯一不必填，后期可以绑定手机号
            $model->rules['referrer_code']='unique:users';//自己的邀请码唯一验证
            //支付密码不做验证,不传支付密码默认为123456
//            $model->rules['password_safe']='required:create|between:6,255|confirmed';
//            $model->rules['password_safe_confirmation']='required_with:password_safe|between:6,255';

            //默认显示的数据
            $model->username=$username=str_random(8);//默认用户编号
            $model->email=$username.'@qq.com';//默认邮箱
            if($user_first){//平台有会员默认第一个用户为推荐人
                //获取推荐人配置
                $tuijian_config=Config::get('summer.hjd::tuijian_config');
                //查找推荐人的字段,referrer_code-邀请码,userphone-手机号,username-用户编号。
                $tuijian_field=$tuijian_config['tuijian_field'];
                $model->tuijian_number=$user_first->$tuijian_field;//默认推荐人号码
            }else{//此次注册第一个用户
                $model->tuid=0;
                $model->tids="0,";
                $model->tdeep=0;
            }
            //生成自己的邀请码
            $model->referrer_code=str_random(12);

            //创建用户之前
            $model->bindEvent('model.beforeCreate', function() use ($model) {
                //如果没传安全密码，默认123456
                if(!$model->password_safe){
                    $model->password_safe=123456;
                }
                if(Input::has('User.tuijian_number')){
                    $tuijian_number=Input::get('User.tuijian_number');
                }elseif(Input::has('tuijian_number')){
                    $tuijian_number=Input::get('tuijian_number');
                }else{
                    $tuijian_number='';
                }
                //获取推荐人配置
                $tuijian_config=Config::get('summer.hjd::tuijian_config');
                //查找推荐人的字段,referrer_code-邀请码,userphone-手机号,username-用户编号。
                $tuijian_field=$tuijian_config['tuijian_field'];
                //推荐人字段是否必须,只限制前台注册，后台注册不填推荐人默认为第一个人
                $tuijian_need=$tuijian_config['tuijian_need'];
                $user_first=UserModel::first();
                $user_tuijian=UserModel::where($tuijian_field,$tuijian_number)->first();
                if($tuijian_need){//必须填写推荐人信息
                    if($user_first){
                        if(!$tuijian_number){
                            throw new ApplicationException('请输入推荐人信息');
                        }
                        if(!$user_tuijian){
                            throw new ApplicationException('请输入正确的推荐人信息');
                        }
                    }
                }else{//推荐人信息非必须
                    if($tuijian_number){
                        //如果传推荐人信息，就判断推荐人信息的准确性
                        if(!$user_tuijian){
                            throw new ApplicationException('请输入正确的推荐人信息');
                        }
                    }
                }
                if($user_tuijian){
                    $model->tuid=$user_tuijian->id;
                    $model->tids=$user_tuijian->tids.$user_tuijian->id.",";
                    $model->tdeep=$user_tuijian->tdeep+1;
                }else{
                    $model->tuid=0;
                    $model->tids="0,";
                    $model->tdeep=0;
                }
            });
            $model->bindEvent('model.beforeUpdate', function() use ($model) {
                //解决只修改登录密码的时候，支付密码置空的问题
                if(!$model->password_safe){
                    unset($model->password_safe);
                }
            });
            //创建用户之后
            $model->bindEvent('model.afterCreate', function() use ($model) {
                //初始化用户钱包
                $usre_id=$model->id;
                WalletModel::make()->initWallet($usre_id);
                //自动激活 因为后台注册不走自动激活的设置,如果启用下面的激活，则前台注册时和用户设置的重复
                $activate_mode = UserSettings::get('activate_mode');
                if ($activate_mode=='auto') {
                    $model->attemptActivation($model->activation_code);
                }
            });


        });
    }

    protected function extendUsersController()
    {
        //扩展表单字段
        UsersController::extendFormFields(function($widget) {
            // Prevent extending of related form instead of the intended User form
            if (!$widget->model instanceof UserModel) {
                return;
            }
            // 移除原字段，方便重新排版,直接注释掉RainLab\User\Models\user\fields除头像外的其他字段
            //安全信息-登录密码和支付密码
            $configFileSafe = plugins_path('summer/userhub/config/safe_fields.yaml');
            $configSafe = Yaml::parse(File::get($configFileSafe));
            $widget->addTabFields($configSafe);
            //基础字段+HJD分销字段
            $configFileBase = plugins_path('summer/userhub/config/base_fields.yaml');
            $configBase = Yaml::parse(File::get($configFileBase));
            $widget->addTabFields($configBase);
            //可用做身份凭证的字段
            $configFileLogin = plugins_path('summer/userhub/config/login_fields.yaml');
            $configLogin = Yaml::parse(File::get($configFileLogin));
            $widget->addFields($configLogin);
            //收款信息
            $configFileBank = plugins_path('summer/userhub/config/bank_fields.yaml');
            $configBank = Yaml::parse(File::get($configFileBank));
            $widget->addTabFields($configBank);
            //扩展信息-居住地址
            $configFileLocation = plugins_path('summer/userhub/config/location_fields.yaml');
            $configLocation = Yaml::parse(File::get($configFileLocation));
            $widget->addTabFields($configLocation);
            //项目扩展信息
//            $configFileProject = plugins_path('summer/userhub/config/project_fields.yaml');
//            $configProject = Yaml::parse(File::get($configFileProject));
//            $widget->addTabFields($configProject);
        });

        // 扩展列表字段
        Event::listen('backend.list.extendColumns', function($widget) {
            // Only for the User controller
            if (!$widget->getController() instanceof \RainLab\User\Controllers\Users) {
                return;
            }
            // Only for the User model
            if (!$widget->model instanceof \RainLab\User\Models\User) {
                return;
            }
            $widget->addColumns([
                'username' => [
                    'label' => e(trans('summer.userhub::lang.user.username')),
                    'searchable'=>true
                ],
                'userphone' => [
                    'label' => e(trans('summer.userhub::lang.user.userphone')),
                    'searchable'=>true
                ],
                'realname' => [
                    'label' => e(trans('summer.userhub::lang.user.realname')),
                    'searchable'=>true
                ],
                'nickname' => [
                    'label' => e(trans('summer.userhub::lang.user.nickname')),
                ],
                'email' => [
                    'label' => e(trans('summer.userhub::lang.user.email')),
                ],
            ]);
            $widget->addColumns([
                'wallets' => [
                    'label' => '钱包',
                    'relation'=>'wallets',
                    'type'=>'partial',
                    'path'=>'~/plugins/summer/hjd/models/comments/_user_wallets.htm',
                    'sortable'=>false,
                ],
                'tuijianinfo' => [
                    'label' => '推荐人',
                    'relation'=>'tuijianinfo',
                    'type'=>'partial',
                    'path'=>'~/plugins/summer/hjd/models/comments/_user.htm',
                    'sortable'=>false,
                ]
            ]);
            $widget->addColumns([
                'levels_code' => [
                    'label' => '当前级别',
                    'relation'=>'levelsinfo',
                    'select'=>'title',
                    'default'=>'暂无',
                ]
            ]);
            $widget->addColumns([
                'yeji_td' => [
                    'label' => '今日团队业绩',
                ],
                'yeji_td_total' => [
                    'label' => '累计团队业绩',
                ],
            ]);



        });
    }

}
